package org.erp.product.infrastructure.config;

import org.erp.product.infrastructure.enums.RepairEventEnum;
import org.erp.product.infrastructure.enums.RepairStatusEnum;

import java.util.HashMap;
import java.util.Map;

public class RepairStateFlow {

    private static final Map<RepairStatusEnum, Map<RepairEventEnum, RepairStatusEnum>> FLOW = new HashMap<>();

    static {
        register(RepairStatusEnum.WAITING_REPAIR, RepairEventEnum.REPAIR, RepairStatusEnum.REPAIRED);
        register(RepairStatusEnum.WAITING_REPAIR, RepairEventEnum.TRANSFER, RepairStatusEnum.TRANSFERRING);
        register(RepairStatusEnum.WAITING_REPAIR, RepairEventEnum.RETURN_BACK, RepairStatusEnum.WAITING_RECYCLE);
        register(RepairStatusEnum.REPAIRED, RepairEventEnum.TRANSFER, RepairStatusEnum.REPAIRED_TRANSFERRING);
        register(RepairStatusEnum.REPAIRED, RepairEventEnum.RETURN_BACK, RepairStatusEnum.WAITING_RECYCLE);
        register(RepairStatusEnum.TRANSFERRING, RepairEventEnum.CONNECT, RepairStatusEnum.CONNECTED);
        register(RepairStatusEnum.TRANSFERRING, RepairEventEnum.OVERRULE, RepairStatusEnum.WAITING_REPAIR);
        register(RepairStatusEnum.REPAIRED_TRANSFERRING, RepairEventEnum.OVERRULE, RepairStatusEnum.REPAIRED);
        register(RepairStatusEnum.WAITING_RECYCLE, RepairEventEnum.CONFIRM_RETURN, RepairStatusEnum.RECYCLED);
    }

    private static void register(RepairStatusEnum source, RepairEventEnum event, RepairStatusEnum target) {
        FLOW.computeIfAbsent(source, k -> new HashMap<>()).put(event, target);
    }

    public static RepairStatusEnum next(RepairStatusEnum current, RepairEventEnum event) {
        Map<RepairEventEnum, RepairStatusEnum> eventMap = FLOW.get(current);
        if (eventMap == null) {
            throw new IllegalStateException("维修当前状态不允许任何业务流转: " + current);
        }
        RepairStatusEnum next = eventMap.get(event);
        if (next == null) {
            throw new IllegalStateException("维修状态 " + current + " 不支持事件 " + event);
        }
        return next;
    }
}
